import { onMounted, onUnmounted } from 'vue'
import { eventsMap } from '@/constants'
import { timeline, logger, eventBus } from '@/instance'

export type HistoryComposition = {
  redo: () => void
  undo: () => void
  reset: () => void
}

enum HistoryType {
  SNAP = 'SNAP',
}

type History = {
  type: HistoryType
  data: any
}
const undoStack: Array<History> = []
const redoStack: Array<History> = []
let current: History | undefined
export function useHistory(): HistoryComposition {
  const redo = () => {
    if (redoStack.length) {
      const item = redoStack.pop()
      undoStack.push(current!)
      current = item
      timeline.attach(item!.data)
      logger.log('composables/history', 'redo', item)
    }
  }
  const undo = () => {
    if (undoStack.length) {
      const item = undoStack.pop()
      redoStack.push(current!)
      current = item
      timeline.attach(item!.data)
      logger.log('composables/history', 'undo', item)
    }
  }
  const reset = () => {
    undoStack.length = 0
    redoStack.length = 0
    current = {
      type: HistoryType.SNAP,
      data: timeline.toJson(),
    }
  }
  const handleTimelineChange = () => {
    redoStack.length = 0
    undoStack.push(current!)
    current = {
      type: HistoryType.SNAP,
      data: timeline.toJson(),
    }

    eventBus.emit(eventsMap.TIMELINE_CHANGE, timeline)
  }

  timeline.on('change', handleTimelineChange)
  timeline.on('load', reset)
  onUnmounted(() => {
    timeline.off('change', handleTimelineChange)
    timeline.off('load', reset)
  })
  logger.log('composables/history', timeline)

  return {
    redo,
    undo,
    reset,
  }
}
